﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ColorApplication.Helper;

namespace ColorApplication.color
{
    public partial class EditContent : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Checking whether Admin or Not. AdminID key is in web.config
            if (Request.QueryString["id"] != null && Request.QueryString["id"] != "" && Request.QueryString["id"] == ConfigurationManager.AppSettings["AdminID"].ToString())
            {
                Clear();
                Response.Cookies[Session.SessionID].Value = "True";
                Response.Cookies[Session.SessionID].Expires = DateTime.Now.AddHours(3);
            }
            else
            {
                Response.Redirect("~/Default.aspx");
            }

//            string script = @"$('.ajax__htmleditor_editor_toptoolbar').each(function (index) {
//                        $(this).html($(this).html() + '<img title='Insert Image' onclick=showImgManager('' + index + '') src='../FileManager/icons/ed_upload_image_n.gif' class='ajax__htmleditor_toolbar_button' /><img title='External URL' onclick=showFileManager('' + index + '') src='../FileManager/icons/inserturl.gif' class='ajax__htmleditor_toolbar_button' /><div style='display:none;float:left;width:100%;padding-top:5px;' id='divImgManager' + index + ''></div>');
//                    });
//                    function openFileManager(index) {
//                        window.open('../FileManager/FileManagerForEditor.aspx?sessionid=<%= Session.SessionID %>&input=' + index, 'myWindow', 'status = 1, height = 650, width = 950, resizable = 0')
//                    }";
//            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "editor", script, true);
        }

        public void Clear()
        {
            // Clear Error And Success label Every Post Bak
            SuccesLabel.Text = "";
            ErrorLabel.Text = "";

        }

        protected void ContentDetailsView_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            try
            {
                // Show Success Message 
                // Grid data Binding
                SuccesLabel.Text = "Record inserted successfully.";
                ErrorLabel.Text = "";
                ContentDetailsView.ChangeMode(DetailsViewMode.Insert);
                ContentGridView.DataBind();
            }
            catch (Exception err)
            {

                ErrorLabel.Text = err.Message.ToString();
            }
        }

        protected void ContentDetailsView_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
        {
            try
            {
                // Show Success Message 
                // Grid data Binding
                SuccesLabel.Text = "Record updated successfully.";
                ErrorLabel.Text = "";
                ContentDetailsView.ChangeMode(DetailsViewMode.Insert);
                ContentGridView.DataBind();
            }
            catch (Exception err)
            {

                ErrorLabel.Text = err.Message.ToString();
            }
        }

        private bool CheckPageNameExistinContent(string PageName)
        {
            // This Function Check Record in Content Table For Duplicate Pair Exist or Not
            // if Record Found Return true
            //else return false

            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = {
                                                new SqlParameter("@PageName", PageName),
                                                
                                            };

                SqlCommand cmd = SQLHelper.GetCommand(con, "CheckPageNameExistinContent", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                return true;
            }

            return false;
        }

        protected void ContentDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            try
            {
                string PageName = e.Values["PageName"].ToString();
                string Text = e.Values["Text"].ToString();

                // This Function Check Record in Content for Duplicate exist or Not
                if (CheckPageNameExistinContent(PageName))
                {
                    ErrorLabel.Text = "Page Name already exists. Duplicate record is not allowed.";
                    e.Cancel = true;
                    //Cancel And Show Error Message
                }
            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();
            }
        }

        protected void ContentDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            try
            {
                string oldPageName = e.OldValues["PageName"].ToString();
                string newPageName = e.NewValues["PageName"].ToString();

                if (oldPageName != newPageName)
                {
                    // This Function Check Record in PageName for Dublicate PageName name exist or Not
                    if (CheckPageNameExistinContent(newPageName))
                    {
                        ErrorLabel.Text = "Page Name already exists. Duplicate record is not allowed.";
                        e.Cancel = true;
                        //Cancel And Show Error Message
                    }
                }

            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();
            }
        }


        protected void ContentGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int ContentID = Convert.ToInt32(e.Keys["Id"].ToString());

                // This Function Check Record in ColorsPageName Table
                //if (CheckRecordColorsPageName(PageNameId, "PageNameId") == true)
                //{
                //    ErrorLabel.Text = "This Arrtibute is used in colors PageName.Delete is not allowed.";
                //    e.Cancel = true;
                //    //Cancel And Show Error Message
                //}
                //else if (CheckPageNamesInPageNamesXPageNamesfamilies(PageNameId) == true)  // This Function Check Record in Sub Color Table
                //{
                //    ErrorLabel.Text = "This Arrtibute is used in PageNames X PageNamesfamilies.Delete is not allowed.";
                //    e.Cancel = true;
                //    //Cancel And Show Error Message
                //}

            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();
            }
        }

        protected void ContentGridView_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                // Change Deatils view Mode to edit
                ContentDetailsView.ChangeMode(DetailsViewMode.Edit);
            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();
            }
        }
    }
}